//
//  YcWebView.swift
//  UICPortal
//
//  Created by 高宇超 on 7/20/17.
//  Copyright © 2017 Yuchao. All rights reserved.
//

import UIKit

typealias WebViewFinishLoadBlock = (_ webView: YcWebView?, _ error: Error?) -> Void

class YcWebView: UIWebView, UIWebViewDelegate {

    var handler: WebViewFinishLoadBlock!
    
    func loadHTML(_ html: String, withCompletionHandler completionHandler: @escaping (_ webView: YcWebView?, _ error: Error?) -> Void) {
        guard let url = URL(string: html.percentEncoding()) else { return }
        let request = URLRequest(url: url)
        self.delegate = self
        self.handler = completionHandler
        self.loadRequest(request)
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        if handler != nil {
            handler(webView as? YcWebView, nil)
            handler = nil
        }
    }
    
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        if handler != nil {
            handler(webView as? YcWebView, error)
            handler = nil
        }
    }
    
}

extension String {
    func percentEncoding() -> String {
        return self.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed)!
    }
}
